from cassaco.models import Category
from cassaco.models import Subcategory

COLORS = ['#006600', '#006633', '#006666', '#006699', '#0066CC', '#0066FF',
              '#996600', '#996633', '#996666', '#996699', '#9966CC', '#9966FF']

def getPieChartUrl(spents):
    colors = COLORS[:]
    totalsDict = {}
    for s in spents:
        catDesc = s.category.description
        totalsDict[catDesc] = totalsDict.get(catDesc, 0) + s.value
    
    total = sum(totalsDict.values())
    output = '<table width="100%" border=1><tr>'
    
    for cat in Category.objects.all():
        desc = cat.description
        value = totalsDict.get(desc, None)
        if not value:
            continue
        
        percent = float((value/total) * 100.0)
        
        onclick = """$("#spentList").load("/cassaco/spent/listByCategory/%d/");
                  """ % cat.id
        output += """<td title='%s %.2fR$' width='%f%%' bgcolor='%s' onclick='%s'
                        style='cursor: pointer;'>
               <font color='white'>%.0f%%</font></td>
               """%(desc, value, percent, colors.pop(), onclick, round(percent,2))
               
    output += '</tr></table>'
    return output

def getSubPieChartUrl(spents, category_id):
    colors = COLORS[:]
    
    d = {}
    for s in spents:
        subcatDesc = s.subcategory.description
        d[subcatDesc] = d.get(subcatDesc, 0) + s.value
        
    total = sum(d.values())
    output = '<table width="100%" border=1><tr>'
    
    for k,v in d.items():
        percent = float((v/total) * 100.0)
        
        onclick = """$("#spentList").load("/cassaco/spent/listBySubcategory/%d/");
                  """ % Subcategory.objects.get(description=k,
                                                category=category_id).id
                  
        output += """<td title='%s %.2fR$' width='%f%%' bgcolor='%s' onclick='%s'
                        style='cursor: pointer;'>
               <font color='white'>%.0f%%</font></td>
               """%(k, v, percent, colors.pop(), onclick, round(percent,2))
               
    output += '</tr></table>'
    return output